package com.jl.obulibrary.servive;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


import com.google.gson.Gson;

import com.jl.obulibrary.driver.RSUSerialDriver;
import com.jl.obulibrary.exceptions.OperationByDSRCException;
import com.jxhc.rsudriver.biz.RsuFrameBuilder;
import com.jxhc.rsudriver.exceptions.FrameReceiveException;
import com.jxhc.rsudriver.exceptions.FrameSendException;
import com.jxhc.rsudriver.model.TransferChannel_res;
import com.xfkj.etcpos.core.ETCPOS;
import com.xfkj.etcpos.core.IEtcPosConfig;
import com.xfkj.etcpos.core.IObuIssuer;
import com.xfkj.etcpos.core.IRSU;
import com.xfkj.etcpos.core.exceps.CryptographyEngineException;
import com.xfkj.etcpos.core.exceps.NoOBUFoundException;
import com.xfkj.etcpos.core.exceps.OBUInvalidException;
import com.xfkj.etcpos.core.exceps.RSUCommunicationException;
import com.xfkj.etcpos.core.model.EtcVehicleInfo;
import com.xfkj.etcpos.core.model.InitialDeviceRequest;
import com.xfkj.etcpos.core.model.ObuSystemInfo;
import com.xfkj.etcpos.core.model.ObuVehicleInfo;
import com.xfkj.etcpos.core.model.TradeRequest;
import com.xfkj.etcpos.core.model.TradeResult;
import com.xfkj.etcpos.core.model.VehicleDimension;

public class OperationByDSRC {
    private static OperationByDSRC instance;

    public static OperationByDSRC getInstance() {
        if (instance == null) {
            instance = new OperationByDSRC();
        }
        return instance;
    }

    private IRSU rsu;
    private IObuIssuer issuer;
    public EtcVehicleInfo etcVehicleInfo;

    public String initEtcPos() {
        //注册RSU驱动
        ETCPOS.registerRsuDriver(new RSUSerialDriver());

        //全局配置参数
        ETCPOS.config()
                .setGlobalProperty(IEtcPosConfig.CRYPTO_TYPE, IEtcPosConfig.LOCAL_PSAM) // 使用本地PSAM加密
                .setGlobalProperty(IEtcPosConfig.LOG_TYPE, IEtcPosConfig.CONSOLE) // 日志采用控制台打印
                .setGlobalProperty(IEtcPosConfig.ROAD_NET_ID, "1201") // 路网编号
                .setGlobalProperty(IEtcPosConfig.STATION_ID, "3333") // 站编号
                .setGlobalProperty(IEtcPosConfig.GET_SECURE_LENGTH, 59);  //GetSecure长度

        return "初始化ETC-POS模式,完成";
    }

    public String initPosRsu(String rsuIp, int power) {
        Log.e("initPosRsu", rsuIp + ";" + power);
        //初始化POS
        try {
            rsu = ETCPOS.etcPos().initRsu(rsuIp, 0, new InitialDeviceRequest() {{
                this.setLaneMode((short) 3);
                this.setPllChannelId((short) 0);
                this.setTxPower((short) power);
                this.setWaitTime((short) 2000);
                this.setTransClass((short) 0);

                this.setPsamSlotNo((short) 1);
                this.setChannelId((short) 1);
                this.setRsuId("1501");
                this.setRsuVersion("01");
            }});
        } catch (Exception e) {
            Log.e("initPosRsu", JSON.toJSONString(e));
        }

        //获取 IObuIssuer
        issuer = ETCPOS.etcPos().getIssuer(rsuIp);
        if (rsu == null) {
            return "初始化5.8G模块失败";
        } else {
            return "初始化5.8G模块成功";
        }
    }

    //读OBU 文件信息
    public EtcVehicleInfo readObuInfo(boolean fetchObuVehicleInfo)
            throws OBUInvalidException, CryptographyEngineException, NoOBUFoundException, RSUCommunicationException {
        //fetchObuVehicleInfo:是否获取解密的车辆信息  读过站信息:false  读IC卡信息:false
        etcVehicleInfo = issuer.fetchOBUInfo(fetchObuVehicleInfo, false, true);
        issuer.SetMMI(true);

        Log.e("obuInfo", new Gson().toJson(etcVehicleInfo));
        return etcVehicleInfo;
    }

    //OBU ESAM的发行和修改
    public String issueOBUByDSRC(String str) throws Exception {

        ObuSystemInfo obuSystemInfo = new ObuSystemInfo();


        ObuVehicleInfo obuVehicleInfo = new ObuVehicleInfo();
        VehicleDimension vehicleDimension = new VehicleDimension();

        JSONObject jsonObject = JSON.parseObject(str);
        obuSystemInfo.setIssuerIdentifier(jsonObject.getString("issuerIdentifier"));
        obuSystemInfo.setContractType(jsonObject.getString("contractType"));
        obuSystemInfo.setContractVersion(jsonObject.getString("contractVersion"));
        obuSystemInfo.setSerialNumber(jsonObject.getString("serialNumber"));
        obuSystemInfo.setDateOfExpire(jsonObject.getString("dateOfExpire"));
        obuSystemInfo.setDateOfIssue(jsonObject.getString("dateOfIssue"));
        obuSystemInfo.setObuStatus(jsonObject.getString("obuStatus"));


        obuVehicleInfo.setPlateNo(jsonObject.getString("plateNo"));
        obuVehicleInfo.setPlateColor(jsonObject.getString("plateColor"));
        obuVehicleInfo.setPlateType(jsonObject.getInteger("plateType"));
        obuVehicleInfo.setUserType(jsonObject.getInteger("userType"));


        vehicleDimension.setLength(jsonObject.getInteger("length"));
        vehicleDimension.setWidth(jsonObject.getInteger("width"));
        vehicleDimension.setHight(jsonObject.getInteger("hight"));

        obuVehicleInfo.setPlateSize(vehicleDimension);


        obuVehicleInfo.setWheelNum(jsonObject.getInteger("wheelNum"));
        obuVehicleInfo.setAxleNum(jsonObject.getInteger("axleNum"));
        obuVehicleInfo.setWheelbase(jsonObject.getInteger("wheelbase"));


        obuVehicleInfo.setLoadAndSeatNum(jsonObject.getInteger("loadAndSeatNum"));
        obuVehicleInfo.setCharacteristic(jsonObject.getString("characteristic"));
        obuVehicleInfo.setEngineNo(jsonObject.getString("engineNo"));


        //发行修改OBU ESAM的系统文件
        if (!issuer.issueObuSystemInfo(obuSystemInfo))
            throw new RSUCommunicationException("发行/修改OBU系统信息失败");

        //发行修改OBU ESAM的车辆信息文件
        if (!issuer.issueObuVehicleInfo(obuSystemInfo.getIssuerIdentifier(), obuSystemInfo.getSerialNumber(), obuVehicleInfo, false))
            throw new RSUCommunicationException("发行/修改OBU车辆信息失败");
        ;

        //释放OBU 并  "哔"的一声
        issuer.SetMMI(true);
        return "";
    }

    //激活OBU
    public String activateObu() throws Exception {
        if (etcVehicleInfo == null) throw new RSUCommunicationException("请先进行激活检测");

        //发行修改OBU ESAM的系统文件
        if (!issuer.activateObu(etcVehicleInfo)) throw new RSUCommunicationException("激活OBU失败");

        //释放OBU 并  "哔"的一声
        issuer.SetMMI(true);
        return "";
    }

    //OBU延期
    public String delayOBU(String str) throws Exception {
        if (etcVehicleInfo == null) throw new RSUCommunicationException("请先读取当前OBU有效期");

        ObuSystemInfo obuSystemInfo = new ObuSystemInfo();

        JSONObject jsonObject = JSON.parseObject(str);
        obuSystemInfo.setIssuerIdentifier(etcVehicleInfo.getIssuerIdentifier());
        obuSystemInfo.setContractType(etcVehicleInfo.getContractType());
        obuSystemInfo.setContractVersion(etcVehicleInfo.getContractVersion());
        obuSystemInfo.setSerialNumber(etcVehicleInfo.getSerialNumber());
        obuSystemInfo.setDateOfExpire(jsonObject.getString("dateOfExpire"));
        obuSystemInfo.setDateOfIssue(jsonObject.getString("dateOfIssue"));
        obuSystemInfo.setObuStatus(etcVehicleInfo.getObuRemoveStatus());

        //发行修改OBU ESAM的系统文件
        if (!issuer.issueObuSystemInfo(obuSystemInfo))
            throw new RSUCommunicationException("OBU延期失败");
        //释放OBU 并  "哔"的一声
        issuer.SetMMI(true);
        return "";
    }

    //OBU交易
    public String obuTrade(String str) throws Exception {
        JSONObject jsonObject = JSON.parseObject(str);
        TradeResult tradeResult;
        try {
            EtcVehicleInfo etcVehicleInfo = issuer.fetchOBUInfo(true, true, true);

            TradeRequest tr = new TradeRequest();
            tr.setParkingTime(2000);//停车时长
            tr.setConsumeMoney(jsonObject.getInteger("money"));
            tr.setObuid(etcVehicleInfo.getObuid());
            tr.setForceObuEntryTraded(false);//非
            // 强制有入场记录
            tradeResult = rsu.exitTrade(etcVehicleInfo, tr, 1500);
            Log.e("TAG", new Gson().toJson(tradeResult));
            return new Gson().toJson(tradeResult);
        } catch (Exception e) {
            e.printStackTrace();
            throw new OperationByDSRCException(e.getMessage());
        }
    }

    public String getRsuVerison() throws Exception {
        String version = rsu.getVersion();
        return version;

    }



}